<!DOCTYPE html>
<html lang="zh_CN">
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>文章内容</title>
  <link rel="stylesheet" href="${ctxPath}/assets/libs/layui/css/layui.css"/>
  <link rel="stylesheet" href="${ctxPath}/assets/module/admin.css">
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
  <style>
    body .tox-tinymce-aux {
      z-index: 19892000;
    }
  </style>
</head>
<body>
<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <form id="addOrUpdateForm" lay-filter="addOrUpdateForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <input name="articleId" type="hidden"/>
        <div class="layui-form-item">
          <label class="layui-form-label layui-form-required">文章内容</label>
          <div class="layui-input-block">
            <textarea name="content" id="contentEditor" placeholder="请输入文章内容" class="layui-textarea"></textarea>
          </div>
        </div>
        <div class="layui-form-item text-right">
          <button class="layui-btn layui-btn-primary" type="button" id="formBackBtn">取消</button>
<!--          <button class="layui-btn layui-btn-warm" lay-filter="formSaveBtn" lay-submit>暂存</button>-->
          <button class="layui-btn" lay-filter="formSubmitBtn" lay-submit>保存</button>
        </div>
      </form>
    </div>
  </div>
</div>
<!-- 加载动画 -->
<div class="page-loading">
  <div class="ball-loader">
    <span></span><span></span><span></span><span></span>
  </div>
</div>
<!-- js部分 -->
<script src="${ctxPath}/assets/libs/layui/layui.js"></script>
<script src="${ctxPath}/assets/js/common.js"></script>
<script src="${ctxPath}/assets/libs/tinymce/tinymce.min.js"></script>
<script>
  layui.use(['layer', 'table', 'tableX', 'notice', 'xnUtil', 'transfer'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;
    var tableX = layui.tableX;
    var admin = layui.admin;
    var form = layui.form;
    var notice = layui.notice;
    var xnUtil = layui.xnUtil;
    var transfer = layui.transfer

    var noticeId = admin.getTempData('noticeId');

    var articleContent = null;

    layer.ready(function(){
      //通过articleId 获取文章内容信息
      admin.req(getProjectUrl() + 'getDetailInfo/' + noticeId,function(res){
          if(res.data != null){
            articleContent = res.data.content;
          }
      },'get')
    })
    
    // 渲染字典下拉
    var typeRenderIns = xmSelect.render({
      el: '#typeBox',
      name: 'type',
      data: xnUtil.getDictDataByDictTypeCode('notice_type', null),
      layVerify: 'required',
      layVerType: 'tips',
      radio: true,
      clickClose: true,
      model: { icon:'hidden', label: { type: 'text' }},
      prop: {
        name: 'name',
        value: 'code'
      },
      tips: '请选择类型'
    });

    //穿梭框
    // var noticeUserTransfer = {};
    // admin.req(getProjectUrl() + 'sysUser/selector', function(res) {
    //   noticeUserTransfer = transfer.render({
    //     elem: '#transferBox',
    //     data: res.data,
    //     showSearch: true,
    //     id: 'transferBox',
    //     title: ['所有用户', '已选择用户'],
    //     parseData: function(res){
    //       return {
    //         "value": res.id, //数据值
    //         "title": res.name //数据标题
    //       }
    //     }
    //   })
    // }, {async: false});

    const image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open('POST', getProjectUrl() + 'sysFileInfo/minio/upload');

      xhr.upload.onprogress = (e) => {
        progress(e.loaded / e.total * 100);
      };

      xhr.onload = () => {
        var res = JSON.parse(xhr.responseText);
        /* {"success":true,"code":200,"message":"请求成功","data":"1609045157607628802","dir":"/","msg":"请求成功"} */
        if (!res.success) {
          layui.notice.msg(res.message, {icon: 2});
          return false;
        } else {
          resolve(getProjectUrl() + 'sysFileInfo/minio/preview?id=' + res.data);
        }
      };

      xhr.onerror = () => {
        reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
      };

      const formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());

      xhr.send(formData);
    });


    // 渲染富文本编辑器
    tinymce.init({
      selector: '#contentEditor',
      height: 525,
      branding: false,
      language: 'zh_CN',
      plugins: 'autoresize code print preview fullscreen searchreplace save autosave link autolink image media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
      toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
                     styleselect fontfamily fontsize | bullist numlist | blockquote subscript superscript removeformat | \
                     table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',
      font_family_formats: "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
      toolbar_mode: 'sliding',
      promotion: false,
      placeholder: '在这里输入正文内容',
      content_style: "img {max-width:100%;}",
      file_picker_types: 'media',
      relative_urls: false,
      remove_script_host: false,
      document_base_url : getProjectUrl(),
      images_upload_handler: image_upload_handler(),
      init_instance_callback: function (editor) {
        if(articleContent != null){
          tinymce.get('contentEditor').setContent(articleContent);
        }
        admin.removeLoading();
      }
    });

    /* 返回按钮点击事件 */
    $('#formBackBtn').click(function () {
        window.location.href = getProjectUrl() + 'notice/index';
    });

    // 表单暂存事件
    // form.on('submit(formSaveBtn)', function (data) {
    //   var content = tinymce.get('contentEditor').getContent();
    //   layer.load(2);
    //   var url = articleId ? getProjectUrl() + '/articleContent/edit' : getProjectUrl() + '/articleContent/add';
    //   data.field.status = 0;
    //   data.field.content = content;
    //   admin.req(url, JSON.stringify(data.field), function(res){
    //     layer.msg(res.message, {icon: 1, time: 1000}, function () {
    //       window.location.href = getProjectUrl() + 'article/index';
    //       return false;
    //     });
    //   }, 'post');
    //   return false;
    // });

    // 表单提交事件
    form.on('submit(formSubmitBtn)', function (data) {
      var content = tinymce.get('contentEditor').getContent();
      if(content === null || content === undefined || content === '') {
        layui.notice.msg('文章内容不能为空', {icon: 2});
        return false;
      }
      layer.load(2);
      var url = getProjectUrl() + 'notice/updateContent';
      data.field.id = noticeId;
      data.field.content = content;
      admin.req(url, JSON.stringify(data.field), function(res){
        layer.msg(res.message, {icon: 1, time: 1000}, function () {
          tinymce.get('contentEditor').isNotDirty = 1;
          window.location.href = getProjectUrl() + 'notice/index';
          return false;
        });
      }, 'post');
      return false;
    });
  });
</script>
</body>
</html>